import React, { Component } from 'react';
import { Table } from 'antd';
import getPagination from './pagination';

export default class BasicTable extends Component {

  namespace = this.props[this.props.namespace];

  componentWillMount() {
    this.getList();
  }

  getList = () => {
    const { dispatch, namespace } = this.props;
    dispatch({
      type: `${namespace}/query`,
      payload: {},
    });
  }

  pageChange = (current) => {
    const { dispatch, namespace } = this.props;
    dispatch({
      type: `${namespace}/query`,
      payload: {
        current,
      }
    });
  }

  onShowSizeChange = (current, size) => {
    const { dispatch, namespace } = this.props;
    dispatch({
      type: `${namespace}/query`,
      payload: {
        size,
      }
    });
  }

  selectedKeysChange = (keys) => {
    const { dispatch, namespace } = this.props;
    dispatch({
      type: `${namespace}/updateState`,
      payload: {
        selectedRowKeys: keys,
      }
    });
  }


  render() {
    const namespace = this.props[this.props.namespace];
    const { rowKey = 'id', showSelected = false, notShow = [], columns = [], dataSource } = this.props;
    const { list, current, size, total, selectedRowKeys } = namespace;
    const realList = dataSource ? namespace[dataSource] : list;
    const showColumns = this.getColumns ?
      this.getColumns(this.columns.filter(c => !notShow.includes(c.dataIndex))) :
      (this.columns || this.props.columns);
    const rowSelection = {
      selectedRowKeys,
      onChange: this.selectedKeysChange,
    };
    return (
      <Table
        columns={showColumns}
        dataSource={realList}
        rowKey={showSelected ? rowKey : null}
        rowSelection={showSelected ? rowSelection : null}
        pagination={getPagination({
          current, size, total,
          onChange: this.pageChange, // 页码改变的回调，参数是改变后的页码及每页条数
          onShowSizeChange: this.onShowSizeChange // pageSize 变化的回调
        })}
      />
    );
  }
}

